<template>
	<fui-nav-bar isOccupy isFixed background="#0052D9" title="工单派工" color="#fff" @leftClick="leftClick" @rightClick="rightClick">
		<fui-icon color="#fff" name="arrowleft"></fui-icon>
		<!--  <template v-slot:right>
      <fui-icon color="#fff" name="plus"></fui-icon>
    </template> -->
	</fui-nav-bar>
	<view class="viewport">
		<view class="warp">
			<view class="segmented" style="">
				<fui-segmented-control :values="values" :current="curNow" @click="sectionChange"></fui-segmented-control>
			</view>
			<view class="head">
				<view class="ipt">
					<u--input
						v-model="searchValue"
						placeholder="请输入"
						activeColor="#359"
						prefixIcon="search"
						prefixIconStyle="font-size: 22px;color: #909399"
						@change="handleSearch"
					></u--input>
				</view>
				<view class="screen" @click="screen">
					<image class="img" src="/static/images/index/shaixuan.svg" mode=""></image>
					筛选
				</view>
			</view>
			<scroll-view
				class="scroll-view"
				:refresher-triggered="refreshing"
				refresher-enabled
				scroll-y="true"
				lower-threshold="20"
				@scrolltolower="onScrollToLower"
				@refresherrefresh="onRefresh"
				refresher-background="#f6f6f6"
			>
				<view class="port">
					<view v-if="currentList.length === 0" class="empty-tip">暂无数据</view>
					<view class="ul" v-else v-for="item in currentList" :key="item.id" @click="particulars(item)">
						<view class="title">{{ item.repairSubject }}</view>
						<view class="li">
							<span class="left">报修单号</span>
							<span>{{ item.repairCode }}</span>
						</view>
						<view class="li">
							<span class="left">设备名称</span>
							<span>{{ item.deviceName }}</span>
						</view>
						<view class="li">
							<span class="left">设备编号</span>
							<span>{{ item.deviceCode }}</span>
						</view>
						<view class="li">
							<span class="left">存放位置</span>
							<span>{{ item.location }}</span>
						</view>

						<view class="footer">
							<span>{{ item.createTime }}</span>
							<view class="audit" :style="{ color: getStatusColor(item.status) }">
								{{ getStatusText(item.status) }}
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script setup>
import { nextTick, ref, onMounted, computed, onUnmounted } from 'vue';
import { getOrderTabs } from '@/pages/api/subpkg_index/dispatching.js';

// 创建响应式引用
const values = ref([
	{
		id: 1,
		name: '未派单(0)'
	},
	{
		id: 2,
		name: '已撤单(0)'
	},
	{
		id: 3,
		name: '已派工(0)'
	}
]);

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 列表数据
const unassignedList = ref([]);
const cancelledList = ref([]);
const assignedList = ref([]);

// 当前显示的列表数据
const currentList = computed(() => {
	switch (curNow.value) {
		case 0:
			return unassignedList.value;
		case 1:
			return cancelledList.value;
		case 2:
			return assignedList.value;
		default:
			return [];
	}
});

// 筛选条件
const filterConditions = ref({
	repairSubject: '', // 报修主题
	deviceName: '', // 设备名称
	location: '', // 存放位置
	emergency: '', // 紧急程度
	status: '', // 审核状态
	startTime: '', // 开始时间
	endTime: '', // 结束时间
	applyUser: '' // 提交人
});

// 监听筛选条件变化
onMounted(() => {
	getOrderData();

	// 添加筛选条件监听
	uni.$on('filterConditions', (data) => {
		console.log('接收到的筛选条件：', data);
		// 确保数据正确赋值
		filterConditions.value = {
			repairSubject: data.repairSubject || '',
			deviceName: data.deviceName || '',
			location: data.location || '',
			emergency: data.emergency || '',
			status: data.status || '',
			startTime: data.startTime || '',
			endTime: data.endTime || '',
			applyUser: data.applyUser || ''
		};
		// 重新获取数据
		currentPage.value = 1;
		getOrderData();
	});
});

// 获取数据
const getOrderData = async () => {
	try {
		// 处理筛选条件
		const params = {
			current: currentPage.value,
			size: pageSize.value,
			repairCode: searchValue.value
		};

		// 添加筛选条件
		if (filterConditions.value.repairSubject) {
			params.repairSubject = filterConditions.value.repairSubject;
		}
		if (filterConditions.value.deviceName) {
			params.deviceName = filterConditions.value.deviceName;
		}
		if (filterConditions.value.location) {
			params.storageLocation = filterConditions.value.location;
		}
		if (filterConditions.value.emergency && filterConditions.value.emergency !== '全部') {
			params.repairLevel = filterConditions.value.emergency;
		}
		if (filterConditions.value.status && filterConditions.value.status !== '全部') {
			params.status = getStatusCode(filterConditions.value.status);
		}
		if (filterConditions.value.startTime) {
			params.applyDateStart = filterConditions.value.startTime;
		}
		if (filterConditions.value.endTime) {
			params.applyDateEnd = filterConditions.value.endTime;
		}
		if (filterConditions.value.applyUser) {
			params.applyUser = filterConditions.value.applyUser;
		}

		console.log('发送给接口的参数：', params);

		const res = await getOrderTabs(params);
		if (res.code === 200) {
			const { unassignedTotal, cancelledTotal, assignedTotal, unassignedList: unList, cancelledList: cList, assignedList: aList, total: totalCount } = res.data;

			total.value = totalCount;

			// 更新tab显示
			values.value = [
				{
					id: 1,
					name: `未派单(${unassignedTotal || 0})`
				},
				{
					id: 2,
					name: `已撤单(${cancelledTotal || 0})`
				},
				{
					id: 3,
					name: `已派工(${assignedTotal || 0})`
				}
			];

			// 更新列表数据
			if (currentPage.value === 1) {
				unassignedList.value = unList || [];
				cancelledList.value = cList || [];
				assignedList.value = aList || [];
			} else {
				unassignedList.value = [...unassignedList.value, ...(unList || [])];
				cancelledList.value = [...cancelledList.value, ...(cList || [])];
				assignedList.value = [...assignedList.value, ...(aList || [])];
			}
		}
	} catch (e) {
		console.error('获取工单数据失败:', e);
		uni.showToast({
			title: '获取数据失败',
			icon: 'none'
		});
	}
};

// 状态码转换函数
const getStatusCode = (status) => {
	const statusMap = {
		待审核: 1,
		驳回: 2,
		已撤回: 3,
		审核中: 4,
		已完成: 5,
		待维修: 6,
		维修中: 7
	};
	return statusMap[status];
};

// 当前选中的tab
const curNow = ref(0);

// tab切换
function sectionChange(e) {
	// e是一个对象，包含index、id和name
	const { index } = e;
	if (typeof index === 'number') {
		curNow.value = index;
	}
}

// 页面加载时获取数据
onMounted(() => {
	getOrderData();
});

// 在组件卸载时移除事件监听
onUnmounted(() => {
	uni.$off('filterConditions');
});

const leftClick = () => {
	uni.reLaunch({
		url: '/pages/index/index'
	});
};
const rightClick = () => {};
const screen = () => {
	uni.navigateTo({
		url: '/subpkg_index/dispatching/audit'
	});
};
//去详情页
const particulars = (item) => {
	uni.navigateTo({
		url: `/subpkg_index/dispatching/particulars?id=${item.id}`
	});
};

//滚动条加载数据
const onScrollToLower = () => {
	if (currentList.value.length >= total.value) {
		uni.showToast({
			title: '没有更多数据了',
			icon: 'none'
		});
		return;
	}
	currentPage.value += 1;
	getOrderData();
};

//下拉刷新
const refreshing = ref(false);
const onRefresh = async () => {
	refreshing.value = true;
	await getOrderData();
	refreshing.value = false;
	uni.showToast({
		title: '刷新成功',
		icon: 'success'
	});
};

// 搜索功能
const searchValue = ref('');
const handleSearch = () => {
	currentPage.value = 1;
	getOrderData();
};

// 获取状态文字
const getStatusText = (status) => {
	const statusMap = {
		5: '已审批',
		6: '待实施',
		7: '实施中',
		8: '已关闭',
		9: '已取消',
		10: '已完成'
	};
	return statusMap[status] || '未知状态';
};

// 获取状态颜色
const getStatusColor = (status) => {
	const colorMap = {
		5: '#0052D9', // 已审批 - 蓝色
		6: '#FF9D00', // 待实施 - 橙色
		7: '#00B42A', // 实施中 - 绿色
		8: '#86909C', // 已关闭 - 灰色
		9: '#F53F3F', // 已取消 - 红色
		10: '#00B42A' // 已完成 - 绿色
	};
	return colorMap[status] || '#86909C';
};
</script>

<style lang="scss" scoped>
page {
	display: flex;
	height: 100%;
	overflow: hidden;
	flex-direction: column;
}
.viewport {
	flex: 1;
	display: flex;
	// height: 100%;
	overflow: hidden;
	flex-direction: column;
}

.warp {
	flex: 1;
	box-sizing: border-box;
	overflow: hidden;
	background-color: #f6f6f6;
	font-family: Arial, Helvetica, sans-serif;
	display: flex;
	flex-direction: column;
	.segmented {
		padding: 24rpx;
		background-color: #fff;
	}

	/*  #ifdef  APP-PLUS || H5 */
	.scroll-view {
		flex: 1;
		height: 100%;
		// height: 80vh;
		padding-bottom: 240rpx;
	}
	/*  #endif  */

	/*  #ifdef  MP-WEIXIN  */
	.scroll-view {
		// flex: 1;
		// height: 100%;
		height: 80vh;
	}
	/*  #endif  */
	.head {
		display: flex;
		align-items: center;
		background-color: #fff;
		height: 120rpx;
		padding: 0 20rpx 20rpx;
		// margin-bottom: 24rpx;
		.ipt {
			flex: 1;
			margin-left: 25rpx;
			height: 100rpx;
			display: flex;
			align-items: center;
		}

		.screen {
			// width: 100rpx;
			display: flex;
			align-items: center;
			justify-content: space-around;
			.img {
				width: 40rpx;
				height: 40rpx;
				margin-right: 10rpx;
			}
		}
	}
	.port {
		.ul {
			margin-bottom: 24rpx;
			background-color: #fff;
			padding: 24rpx 30rpx;
			border-radius: 12rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

			.title {
				color: #0052d9;
				font-size: 32rpx;
				font-weight: 600;
				height: 80rpx;
				line-height: 80rpx;
			}

			.li {
				color: #666;
				height: 50rpx;
				line-height: 50rpx;
				font-size: 28rpx;

				.left {
					color: #333;
					margin-right: 30rpx;
					font-weight: 500;
				}
			}

			.footer {
				display: flex;
				height: 80rpx;
				align-items: center;
				justify-content: space-between;
				margin-top: 16rpx;
				border-top: 1rpx solid #eee;
				padding-top: 16rpx;

				span {
					color: #999;
					font-size: 26rpx;
				}
			}
		}
	}
}
.audit {
	border-radius: 25rpx;
	height: 48rpx;
	min-width: 120rpx;
	padding: 0 20rpx;
	display: flex;
	font-size: 28rpx;
	align-items: center;
	justify-content: center;
	border: 1rpx solid currentColor;
}

.empty-tip {
	text-align: center;
	color: #999;
	padding: 40rpx 0;
	font-size: 28rpx;
}

.ul {
	margin-bottom: 24rpx;
	background-color: #fff;
	padding: 24rpx 30rpx;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

	.title {
		color: #0052d9;
		font-size: 32rpx;
		font-weight: 600;
		height: 80rpx;
		line-height: 80rpx;
	}

	.li {
		color: #666;
		height: 50rpx;
		line-height: 50rpx;
		font-size: 28rpx;

		.left {
			color: #333;
			margin-right: 30rpx;
			font-weight: 500;
		}
	}

	.footer {
		display: flex;
		height: 80rpx;
		align-items: center;
		justify-content: space-between;
		margin-top: 16rpx;
		border-top: 1rpx solid #eee;
		padding-top: 16rpx;

		span {
			color: #999;
			font-size: 26rpx;
		}
	}
}
</style>